package com.dana.system.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.core.constants.Constants;
import com.core.domain.TableDataInfo;
import com.core.enums.ResultCode;
import com.dana.security.exception.ServiceException;
import com.dana.system.domain.es.QuestionES;
import com.dana.system.domain.question.Question;
import com.dana.system.domain.question.dto.QueryQuestionDTO;
import com.dana.system.domain.question.dto.QuestionAddDTO;
import com.dana.system.domain.question.dto.QuestionEditDTO;
import com.dana.system.domain.question.vo.QuestionDetailVO;
import com.dana.system.domain.question.vo.QuestionVO;
import com.dana.system.elasticsearch.QuestionRepository;
import com.dana.system.manager.QuestionCacheManager;
import com.dana.system.mapper.question.QuestionMapper;
import com.dana.system.service.question.IQuestionService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import java.util.stream.Collectors;

@Service
public class IQuestionServiceImpl  extends ServiceImpl<QuestionMapper, Question>
        implements IQuestionService {
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private QuestionCacheManager questionCacheManager;

    /**
     * 返回题目集合
     *返回的题目集合不仅要在题目模块进行展示,还要在竞赛编辑模块展示,已经选择的题目就不会再出现在竞赛编辑页面上
     * @param queryQuestionDTO
     * @return
     */
    @Override
    public List<QuestionVO> list(QueryQuestionDTO queryQuestionDTO) {
        String excludeStr = queryQuestionDTO.getExcludeStr();
        //如果传递的题目id参数为空,直接返回全部列表,
        //传递的题目id是已经选择的,使用字符串+;进行分割,如果传递的题目id为空,返回所有题目,如果不为空,将题目id所对应的题目不返回,返回未选择的
        if (StrUtil.isNotEmpty(excludeStr)) {
            //解析前端传来的字符串(参数是以分号分割),拿到传进来的参数进行解析
            String[] excludeIdArr = excludeStr.split(Constants.SPLIT_SEM);
            //利用stream流转换成Long类型id
            Set<Long> excludeIdSet = Arrays
                    .stream(excludeIdArr)
                    .map(Long::valueOf)
                    .collect(Collectors.toSet());

            //将传来的题目id赋值给queryQuestionDTO,带去数据库进行操作
            queryQuestionDTO.setExcludeIdSet(excludeIdSet);
        }
        //PageHelper  mybatis提供的分页插件,可以自动分页,
        //假如传递第一页,前10条,下次传递第2页,就会从第10条数据开始返回后边的数据
        PageHelper.startPage(queryQuestionDTO.getPageNum(), queryQuestionDTO.getPageSize());
        return questionMapper.selectQuestionList(queryQuestionDTO);
    }


    /**
     * 添加题目
     * @param questionAddDTO
     * @return
     */
    @Override
    public boolean add(QuestionAddDTO questionAddDTO) {
        Question question=new Question();
        //查询数据库是否有重复的题目,否则不进行添加
        //select * from question where title=#{title}
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                .eq(Question::getTitle, questionAddDTO.getTitle()));

        if (CollectionUtil.isNotEmpty(questionList)){
            throw new ServiceException(ResultCode.FAILED_ALREADY_EXISTS);
        }
        //利用hutools进行对象转换,将questionAddDTO转换成question
        BeanUtil.copyProperties(questionAddDTO,question);
        //将数据存储到数据库中
        int insert = questionMapper.insert(question);
        if (insert<=0){
            return false;
        }
        //将新增题目缓存到es中,同步给es即可
        QuestionES questionES=new QuestionES();
        BeanUtil.copyProperties(question,questionES);
        questionRepository.save(questionES);
        //在答题页面的上一题下一题功能中,我们先将题目id进行了缓存
        //同时管理员新增题目的时候也要将题目id添加到缓存的题目顺序中,不然redis永远只会存放老数据
        questionCacheManager.addCache(question.getQuestionId());
        return true;
    }


    /**
     * 获取题目详情
     * @param questionId
     */
    @Override
    public QuestionDetailVO detail(Long questionId) {
        Question question = questionMapper.selectById(questionId);
        if (question==null){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }

        //将数据库中的question取出赋值给questionDetailVO,将vo返回前端
        QuestionDetailVO questionDetailVO=new QuestionDetailVO();
        BeanUtil.copyProperties(question,questionDetailVO);
        return questionDetailVO;
    }

    /**
     * 修改题目
     * @param questionEditDTO
     * @return
     */
    @Override
    public int edit(QuestionEditDTO questionEditDTO) {
        Question oldquestion = questionMapper.selectById(questionEditDTO.getQuestionId());
        if (oldquestion == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        oldquestion.setTitle(questionEditDTO.getTitle());
        oldquestion.setDifficulty(questionEditDTO.getDifficulty());
        oldquestion.setTimeLimit(questionEditDTO.getTimeLimit());
        oldquestion.setSpaceLimit(questionEditDTO.getSpaceLimit());
        oldquestion.setContent(questionEditDTO.getContent());
        oldquestion.setQuestionCase(questionEditDTO.getQuestionCase());
        oldquestion.setDefaultCode(questionEditDTO.getDefaultCode());
        oldquestion.setMainFuc(questionEditDTO.getMainFuc());
        //将修改后的题目缓存到es中
        QuestionES questionES = new QuestionES();
        BeanUtil.copyProperties(oldquestion, questionES);
        questionRepository.save(questionES);
        return questionMapper.updateById(oldquestion);
    }

    /**
     * 删除题目
     * @param questionId
     * @return
     */
    @Override
    public int delete(Long questionId) {
        Question question = questionMapper.selectById(questionId);
        if (question==null){
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        //删除题目之后将删除信息告知es,让es也进行删除操作
        questionRepository.deleteById(questionId);

        //在答题页面的上一题下一题功能中,我们先将题目id进行了缓存
        //同时管理员删除题目的时候也要将题目id从缓存的题目顺序中删除,不然redis永远只会存放老数据
        questionCacheManager.deleteCache(question.getQuestionId());
        return questionMapper.deleteById(questionId);
    }
    
}
